﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using HttpTunnel;
using log4net;

namespace HttpTunnelServer
{
    class Program
    {
        private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();

                var config = GetConfig();

                Listener.Initialize(config);

                Listener.Start();

                Console.Write("Listening...");

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                new EventLog { Source = "iSafe Browser Web Page Forward Server" }.WriteEntry(ex.Message, EventLogEntryType.Error);
                Logger.Debug("Main", ex);
            }
        }

        private static Config GetConfig()
        {
            var proxy = ConfigurationManager.AppSettings["proxy"].Split(':');
            var configFolder = string.Format("{0}\\conf\\", Environment.CurrentDirectory);

            var config = new Config
                {
                    Port = int.Parse(ConfigurationManager.AppSettings["listening-port"]),
                    Proxy = new IPEndPoint(IPAddress.Parse(proxy[0]), int.Parse(proxy[1])),
                    ErrorPageTemplate = File.ReadAllText(string.Format("{0}errorPageTemplate.htm", configFolder)),
                    OutOfDatePageTemplate = File.ReadAllText(string.Format("{0}outofdatePageTemplate.htm", configFolder)),
                    UserAgent = ConfigurationManager.AppSettings["user-agent"],
                    WhiteList = File.ReadAllLines(string.Format("{0}whitelist.conf", configFolder)),
                    BlackList = File.ReadAllLines(string.Format("{0}blacklist.conf", configFolder)),
                    InternalList = File.ReadAllLines(string.Format("{0}internallist.conf", configFolder)),
                    Keywords = File.ReadAllLines(string.Format("{0}keywords.conf", configFolder)),
                    MinBrowserVersion = Version.Parse(ConfigurationManager.AppSettings["min-browser-version"]),
                    MaxRequestLength = int.Parse(ConfigurationManager.AppSettings["max-request-length"]),
                    IsFilterOn = "on".Equals(ConfigurationManager.AppSettings["filter-state"])
                };
            return config;
        }
    }
}
